package com.irate.fragment;

import java.util.List;
import java.util.Locale;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.adapter.SearchFriendAdapter;
import com.irate.cache.ImageCache.ImageCacheParams;
import com.irate.cache.ImageFetcher;
import com.irate.dao.UserDAO;
import com.irate.dao.UserSearchFriendDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.UserSearchFriend;
import com.irate.provider.ContentManager;

public class FriendAddFriend extends Fragment {

	protected ImageFetcher imageFetcher;
	protected static final String IMAGE_CACHE_DIR = "thumbs";
	protected int mImageThumbSize = 100;
	protected EditText textSearch;
	protected ImageView butSearch;
	protected ListView friendList;
	protected SearchFriendAdapter adapter;
	protected UserDAO userDAO;
	protected ProgressDialog dialog;
	protected UserSearchFriendDAO userSearchDAO;
	protected LinearLayout content_friend_not_fault;
	protected TextView friendNotFaultInfo;
	protected Button but_send;
	protected Button but_cancel;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.friend_add_friend, null);
	}

	@Override
	public void onResume() {
		super.onResume();
		imageFetcher.setExitTasksEarly(false);
	}

	@Override
	public void onPause() {
		super.onPause();
		imageFetcher.setPauseWork(false);
		imageFetcher.setExitTasksEarly(true);
		imageFetcher.flushCache();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		imageFetcher.closeCache();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		init();
		execute();
	}

	private void init() {
		userDAO = new UserDAO();

		ImageCacheParams cacheParams = new ImageCacheParams(getActivity(),
				IMAGE_CACHE_DIR);

		cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of
		imageFetcher = new ImageFetcher(getActivity(), mImageThumbSize);
		imageFetcher.setLoadingImage(R.drawable.user);
		imageFetcher.addImageCache(
				((FragmentActivity) getActivity()).getSupportFragmentManager(),
				cacheParams);

		textSearch = (EditText) getActivity().findViewById(R.id.textSearch);
		butSearch = (ImageView) getActivity().findViewById(R.id.buttonSearch);

		friendList = (ListView) getActivity().findViewById(R.id.list_friend);
		content_friend_not_fault = (LinearLayout) getActivity().findViewById(
				R.id.search_friend_content_not_fault);
		friendNotFaultInfo = (TextView) getActivity().findViewById(
				R.id.search_friend_not_fault_string);
		but_send = (Button) getActivity().findViewById(
				R.id.search_friend_notfault_send_request_yes);
		but_cancel = (Button) getActivity().findViewById(
				R.id.search_friend_notfault_send_request_no);

		userSearchDAO = new UserSearchFriendDAO();
	}

	private void execute() {
		butSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (textSearch.getText().toString().trim().equals("")) {
					Toast.makeText(getActivity(), "Input not fault",
							Toast.LENGTH_LONG).show();
				} else {

					doSearch();
				}
			}

		});

		textSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					if (textSearch.getText().toString().trim().equals("")) {
						Toast.makeText(getActivity(), "Input not fault",
								Toast.LENGTH_LONG).show();
					} else {
						doSearch();
					}
					return true;
				}

				return false;
			}
		});

		loadData();
	}

	private void loadData() {
		if (ContentManager.getInstance().getStrSearchFriendAddFriend() != null
				&& !ContentManager.getInstance().getStrSearchFriendAddFriend()
						.equals("")) {
			textSearch.setText(ContentManager.getInstance()
					.getStrSearchFriendAddFriend());
			// doSearch(ContentManager.getInstance().getStrSearchFriendAddFriend());
		}
		
		dialog = ProgressDialog.show(getActivity(),
				getResources().getString(R.string.recommand_friend), getResources()
						.getString(R.string.loading), true);

		userDAO.getRecommendList(handlerRecomendList, getActivity(), dialog);
	}

	private void doSearch() {

		friendList.setVisibility(View.VISIBLE);

		final String keyw = textSearch.getText().toString().trim()
				.toLowerCase(Locale.getDefault());

		dialog = ProgressDialog.show(getActivity(),
				getResources().getString(R.string.searching), getResources()
						.getString(R.string.loading), true);

		userDAO.searchFriend(keyw, handlerSearchFriend, getActivity(), dialog);

	}

	protected synchronized void fillDataToListView(List<UserSearchFriend> values) {
		adapter = new SearchFriendAdapter(values, getActivity(), imageFetcher);
		friendList.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		friendList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
					imageFetcher.setPauseWork(true);
				} else {
					imageFetcher.setPauseWork(false);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});

	}

	AsyncHttpResponseHandler handlerSearchFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			List<UserSearchFriend> lst = userSearchDAO
					.parseListData(new String(response));
			ContentManager.getInstance().setStrSearchFriendAddFriend(
					textSearch.getText().toString().trim());

			fillDataToListView(lst);
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

				content_friend_not_fault.setVisibility(View.VISIBLE);

				setUpContentFriendNotFault();

				friendList.setVisibility(View.GONE);

			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerRecomendList = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			List<UserSearchFriend> lst = userSearchDAO
					.parseListData(new String(response));

			fillDataToListView(lst);
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

	protected void setUpContentFriendNotFault() {
		friendNotFaultInfo.setText("Friend not found!\nSend invite to\n \""
				+ textSearch.getText().toString().trim() + "\" ?");
		but_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				content_friend_not_fault.setVisibility(View.GONE);
				dialog = ProgressDialog.show(getActivity(),
						getResources().getString(R.string.invitation_friend), getResources()
								.getString(R.string.loading), true);
				userDAO.inviteFriend(textSearch.getText().toString().trim(), handlerSendInvitation, getActivity(), dialog);
				
			}
		});

		but_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				content_friend_not_fault.setVisibility(View.GONE);
			}
		});
	}
	
	AsyncHttpResponseHandler handlerSendInvitation = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
			
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

}